<template>
  <div class="dashboard">
    <!-- 统计概览 -->
    <div class="stats-grid responsive-grid grid-cols-4 mb-3">
      <!-- 强制刷新按钮 -->
      <div class="refresh-controls" style="grid-column: 1 / -1; margin-bottom: 16px; text-align: right;">
        <el-button type="primary" @click="forceRefreshAllData" :loading="dataLoading" size="small">
          <el-icon><Refresh /></el-icon>
          强制刷新所有数据
        </el-button>
        <el-button @click="debugCurrentState" type="info" plain size="small">
          <el-icon><DataAnalysis /></el-icon>
          调试当前状态
        </el-button>
      </div>

      <el-card
        v-for="stat in (overviewStats || [])"
        :key="stat.title"
        class="stats-card"
        shadow="hover"
      >
        <div class="stat-content">
          <div class="stat-icon" :style="{ backgroundColor: stat.color + '20' }">
            <el-icon :style="{ color: stat.color }" :size="32">
              <component :is="stat.icon" />
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-title">{{ stat.title }}</div>
            <div class="stat-trend" :class="stat.trend > 0 ? 'up' : 'down'" v-if="stat.trend !== 0">
              <el-icon><ArrowUp v-if="stat.trend > 0" /><ArrowDown v-else /></el-icon>
              {{ Math.abs(stat.trend) }}%
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row mb-3">
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">模块类型分布</span>
              <el-button size="small" @click="refreshModuleTypeChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
        <ModuleTypeChart :data="moduleTypeData" :loading="moduleTypeLoading" />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">依赖关系图</span>
              <el-button size="small" @click="refreshDependencyChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
        <DependencyChart :data="dependencyData" :loading="dependencyLoading" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 热门模块和系统概览 -->
    <el-row :gutter="20" class="info-row">
      <el-col :span="14">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">热门模块</span>
              <el-button size="small" @click="refreshTopModules">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="top-modules">
            <el-table :data="(topModules || [])" style="width: 100%" size="small">
              <el-table-column prop="name" label="模块名称" show-overflow-tooltip />
              <el-table-column prop="component" label="部件" width="120" />
              <el-table-column prop="deps_count" label="依赖数" width="80" align="center" />
              <el-table-column prop="depended_by_count" label="被依赖数" width="100" align="center" />
              <el-table-column prop="size" label="大小" width="100" align="right">
                <template #default="{ row }">
                  {{ formatSize(row.size) }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card shadow="never">
          <template #header>
            <div class="card-header">
              <span class="title">系统概览</span>
            </div>
          </template>
          <div class="system-overview">
            <div class="overview-item">
              <div class="overview-label">总模块数</div>
              <div class="overview-value">{{ systemStats.totalModules }}</div>
            </div>
            <div class="overview-item">
              <div class="overview-label">总部件数</div>
              <div class="overview-value">{{ systemStats.totalComponents }}</div>
            </div>
            <div class="overview-item">
              <div class="overview-label">总符号数</div>
              <div class="overview-value">{{ systemStats.totalSymbols }}</div>
            </div>
            <div class="overview-item">
              <div class="overview-label">总依赖关系</div>
              <div class="overview-value">{{ systemStats.totalDependencies }}</div>
            </div>
            <div class="overview-item">
              <div class="overview-label">平均依赖深度</div>
              <div class="overview-value">{{ systemStats.avgDependencyDepth }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ArrowUp, ArrowDown, Refresh, Monitor, Grid, Cpu, DataAnalysis } from '@element-plus/icons-vue'
import ModuleTypeChart from '@/components/charts/ModuleTypeChart.vue'
import DependencyChart from '@/components/charts/DependencyChart.vue'
import { moduleApi } from '@/api/modules'
import { useAppStore } from '@/stores/app'

// 响应式数据
const moduleTypeData = ref([])
const dependencyData = ref([])
const topModules = ref([])
const moduleTypeLoading = ref(false)
const dependencyLoading = ref(false)
const topModulesLoading = ref(false)
const systemStatsLoading = ref(false)
const dataLoading = ref(false) // 全局loading状态

// Store
const appStore = useAppStore()

// 系统统计
const systemStats = reactive({
  totalModules: 0,
  totalComponents: 0,
  totalSymbols: 0,
  totalDependencies: 0,
  avgDependencyDepth: 0
})

// 概览统计 - 基于真实系统数据的计算属性
const overviewStats = computed(() => {
  try {
    return [
      {
        title: '总模块数',
        value: (systemStats?.totalModules || 0).toLocaleString(),
        icon: 'Grid',
        color: '#409eff',
        trend: 0 // 暂时设为0，后续可添加趋势计算
      },
      {
        title: '总部件数',
        value: (systemStats?.totalComponents || 0).toLocaleString(),
        icon: 'Monitor',
        color: '#67c23a',
        trend: 0
      },
      {
        title: '依赖关系',
        value: (systemStats?.totalDependencies || 0).toLocaleString(),
        icon: 'DataAnalysis',
        color: '#e6a23c',
        trend: 0
      },
      {
        title: '符号总数',
        value: formatLargeNumber(systemStats?.totalSymbols || 0),
        icon: 'Cpu',
        color: '#f56c6c',
        trend: 0
      }
    ]
  } catch (error) {
    console.error('Error computing overviewStats:', error)
    return []
  }
})

// 方法
const formatSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

const formatLargeNumber = (num) => {
  try {
    if (num == null || num === undefined || isNaN(num)) return '0'
    if (num === 0) return '0'
    const number = Number(num)
    if (number < 1000) return number.toString()
    if (number < 1000000) return (number / 1000).toFixed(1) + 'K'
    if (number < 1000000000) return (number / 1000000).toFixed(1) + 'M'
    return (number / 1000000000).toFixed(1) + 'B'
  } catch (error) {
    console.error('Error formatting large number:', error)
    return '0'
  }
}

const loadModuleTypeData = async (productName, version) => {
  if (!productName) return

  moduleTypeLoading.value = true
  try {
    const response = await moduleApi.getModuleTypeDistribution(productName, version)
    const data = response?.data || []
    const dataArray = Array.isArray(data) ? data : []
    moduleTypeData.value = dataArray.length > 0 ? dataArray : [
      { value: 0, name: '无数据' }
    ]
    console.log('Module type data loaded:', dataArray.length, 'items')
  } catch (error) {
    console.error('Failed to load module type data:', error)
    moduleTypeData.value = [
      { value: 0, name: '加载失败' }
    ]
  } finally {
    moduleTypeLoading.value = false
  }
}

const loadDependencyData = async (productName, version) => {
  if (!productName) return

  dependencyLoading.value = true
  try {
    dependencyData.value = [] // 依赖关系图暂未实现，保持为空
    console.log('Dependency data cleared (not implemented)')
  } catch (error) {
    console.error('Failed to load dependency data:', error)
    dependencyData.value = []
  } finally {
    dependencyLoading.value = false
  }
}

const loadTopModules = async (productName, version) => {
  if (!productName) return

  topModulesLoading.value = true
  try {
    const response = await moduleApi.getTopModules(productName, version, 10)
    const data = response?.data || []
    const dataArray = Array.isArray(data) ? data : []
    topModules.value = dataArray
    console.log('Top modules loaded:', dataArray.length, 'items')
  } catch (error) {
    console.error('Failed to load top modules:', error)
    topModules.value = []
  } finally {
    topModulesLoading.value = false
  }
}

const loadSystemStats = async (productName, version) => {
  if (!productName) return

  systemStatsLoading.value = true
  try {
    const response = await moduleApi.getModuleStats(productName, version)

    if (response?.data) {
      const newStats = {
        totalModules: response.data.totalModules || 0,
        totalComponents: response.data.totalComponents || 0,
        totalSymbols: response.data.totalSymbols || 0,
        totalDependencies: response.data.totalDependencies || 0,
        avgDependencyDepth: response.data.avgDependencyDepth || 0
      }

      Object.assign(systemStats, newStats)
    } else {
      Object.assign(systemStats, {
        totalModules: 0,
        totalComponents: 0,
        totalSymbols: 0,
        totalDependencies: 0,
        avgDependencyDepth: 0
      })
    }
  } catch (error) {
    console.error('Failed to load system stats:', error)
    Object.assign(systemStats, {
      totalModules: 0,
      totalComponents: 0,
      totalSymbols: 0,
      totalDependencies: 0,
      avgDependencyDepth: 0
    })
  } finally {
    systemStatsLoading.value = false
  }
}

const refreshModuleTypeChart = () => {
  if (appStore.currentProduct && appStore.currentVersion) {
    loadModuleTypeData(appStore.currentProduct, appStore.currentVersion)
  }
}

const refreshDependencyChart = () => {
  if (appStore.currentProduct && appStore.currentVersion) {
    loadDependencyData(appStore.currentProduct, appStore.currentVersion)
  }
}

const refreshTopModules = () => {
  if (appStore.currentProduct && appStore.currentVersion) {
    loadTopModules(appStore.currentProduct, appStore.currentVersion)
  }
}

// 监听产品变化
watch(
  () => {
    try {
      return [appStore?.currentProduct, appStore?.currentVersion]
    } catch (error) {
      console.error('Error in watch getter:', error)
      return [null, null]
    }
  },
  (newValues, oldValues) => {
    try {
      // 安全解构
      const newProduct = newValues?.[0]
      const newVersion = newValues?.[1]
      const oldProduct = oldValues?.[0]
      const oldVersion = oldValues?.[1]

      // 安全处理可能undefined的值
      const newProd = newProduct?.toString?.() || ''
      const newVer = newVersion?.toString?.() || ''
      const oldProd = oldProduct?.toString?.() || ''
      const oldVer = oldVersion?.toString?.() || ''

      console.log('Watcher triggered:', {
        newProd,
        newVer,
        oldProd,
        oldVer,
        hasNewProduct: !!(newProd && newVer),
        hasChanged: (newProd !== oldProd || newVer !== oldVer)
      })

      // 只有在有有效的产品信息且发生了变化时才重新加载数据
      if ((newProd && newVer) && (newProd !== oldProd || newVer !== oldVer)) {
        console.log(`Product changed from ${oldProd}/${oldVer} to ${newProd}/${newVer}, reloading data`)

        // 防抖处理，避免频繁调用
        if (typeof loadDataForProduct === 'function') {
          loadDataForProduct(newProd, newVer)
        } else {
          console.error('loadDataForProduct is not available')
        }
      } else if (!newProd || !newVer) {
        console.log('No valid product selected, skipping data load')
      }
    } catch (error) {
      console.error('Error in product watcher callback:', error)
      // 确保即使出错也不会中断应用
    }
  },
  { immediate: true }
)

// 加载指定产品的数据
const loadDataForProduct = async (productName, version) => {
  if (!productName || !version) return

  dataLoading.value = true
  console.log(`Starting to load data for product: ${productName}/${version}`)

  try {
    // 确保每个load函数都存在并且是函数
    const loadTasks = []
    if (typeof loadModuleTypeData === 'function') {
      loadTasks.push(loadModuleTypeData(productName, version))
    }
    if (typeof loadDependencyData === 'function') {
      loadTasks.push(loadDependencyData(productName, version))
    }
    if (typeof loadTopModules === 'function') {
      loadTasks.push(loadTopModules(productName, version))
    }
    if (typeof loadSystemStats === 'function') {
      loadTasks.push(loadSystemStats(productName, version))
    }

    if (loadTasks.length > 0) {
      try {
        await Promise.all(loadTasks)
        console.log(`All data loaded successfully for product: ${productName}/${version}`)
      } catch (promiseError) {
        console.error('Error in Promise.all:', promiseError)
        // 继续执行，不中断加载
      }
    }
  } catch (error) {
    console.error('Failed to load data for product:', productName, version, error)
    // 不抛出错误，让页面继续运行
  } finally {
    dataLoading.value = false
  }
}

// 强制刷新所有数据
const forceRefreshAllData = async () => {
  if (!appStore.currentProduct || !appStore.currentVersion) {
    console.warn('No current product selected')
    return
  }

  dataLoading.value = true

  try {
    // 分别调用API，确保数据按顺序加载
    await loadSystemStats(appStore.currentProduct, appStore.currentVersion)
    await new Promise(resolve => setTimeout(resolve, 100))

    await loadModuleTypeData(appStore.currentProduct, appStore.currentVersion)
    await new Promise(resolve => setTimeout(resolve, 100))

    await loadTopModules(appStore.currentProduct, appStore.currentVersion)
    await new Promise(resolve => setTimeout(resolve, 100))

    await loadDependencyData(appStore.currentProduct, appStore.currentVersion)
  } catch (error) {
    console.error('Force refresh failed:', error)
  } finally {
    dataLoading.value = false
  }
}

// 调试当前状态
const debugCurrentState = () => {
  console.log('Current Dashboard State:', {
    currentProduct: appStore.currentProduct,
    systemStats: {
      totalModules: systemStats.totalModules,
      totalComponents: systemStats.totalComponents,
      totalSymbols: systemStats.totalSymbols,
      totalDependencies: systemStats.totalDependencies,
      avgDependencyDepth: systemStats.avgDependencyDepth
    },
    loadingStates: {
      dataLoading: dataLoading.value,
      systemStatsLoading: systemStatsLoading.value,
      moduleTypeLoading: moduleTypeLoading.value,
      topModulesLoading: topModulesLoading.value
    }
  })
}

// 生命周期
onMounted(() => {
  if (appStore.currentProduct && appStore.currentVersion) {
    loadDataForProduct(appStore.currentProduct, appStore.currentVersion)
  }
})
</script>

<style lang="scss" scoped>
.dashboard {
  // 深色模式支持
  .stats-grid {
    .stats-card {
      // 卡片深色模式背景
      background: var(--el-bg-color);
      border-color: var(--el-border-color);

      &:hover {
        box-shadow: var(--el-box-shadow-light);
      }

      .stat-content {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 64px;
          height: 64px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          transition: all 0.3s ease;

          // 深色模式下图标背景更明显
          @at-root .dark .dashboard .stats-grid .stats-card .stat-content .stat-icon {
            background: rgba(255, 255, 255, 0.05);
          }
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: 600;
            line-height: 1;
            margin-bottom: 8px;
            color: var(--el-text-color-primary);
            transition: color 0.3s ease;
          }

          .stat-title {
            font-size: 14px;
            color: var(--el-text-color-regular);
            margin-bottom: 4px;
            transition: color 0.3s ease;
          }

          .stat-trend {
            font-size: 12px;
            display: flex;
            align-items: center;

            &.up {
              color: var(--el-color-success);
            }

            &.down {
              color: var(--el-color-danger);
            }

            .el-icon {
              margin-right: 4px;
            }
          }
        }
      }
    }
  }

  .charts-row {
    .el-card {
      background: var(--el-bg-color);
      border-color: var(--el-border-color);

      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: var(--el-text-color-primary);

        .title {
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
      }
    }
  }

  .info-row {
    .el-card {
      background: var(--el-bg-color);
      border-color: var(--el-border-color);

      .card-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: var(--el-text-color-primary);

        .title {
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
      }
    }
  }

  .top-modules {
    .el-table {
      --el-table-header-bg-color: var(--el-fill-color-light);
      --el-table-border-color: var(--el-border-color-lighter);
      --el-table-text-color: var(--el-text-color-primary);
      --el-table-header-text-color: var(--el-text-color-primary);

      // 表格行深色模式样式
      --el-table-row-hover-bg-color: var(--el-fill-color-light);
      --el-table-current-row-bg-color: var(--el-fill-color);
    }

    // 表格链接深色模式
    :deep(.el-link) {
      color: var(--el-color-primary);

      &:hover {
        color: var(--el-color-primary-light-3);
      }
    }
  }

  .system-overview {
    .overview-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      transition: all 0.3s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: var(--el-fill-color-light);
        border-radius: 4px;
        margin: 0 -8px;
        padding: 12px 8px;
      }

      .overview-label {
        font-size: 14px;
        color: var(--el-text-color-regular);
        transition: color 0.3s ease;
      }

      .overview-value {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        transition: color 0.3s ease;
      }
    }
  }

  // 刷新控件深色模式
  .refresh-controls {
    .el-button {
      // 按钮深色模式过渡
      transition: all 0.3s ease;
    }
  }
}

// 深色模式全局样式覆盖
:deep(.el-card) {
  background: var(--el-bg-color);
  border-color: var(--el-border-color);
  transition: all 0.3s ease;

  .el-card__header {
    border-bottom-color: var(--el-border-color-lighter);
    background: var(--el-bg-color);
  }

  .el-card__body {
    background: var(--el-bg-color);
  }
}

// 表格深色模式优化
:deep(.el-table) {
  background: var(--el-bg-color);
  color: var(--el-text-color-primary);

  th.el-table__cell {
    background: var(--el-fill-color-light);
    border-bottom-color: var(--el-border-color-lighter);
    color: var(--el-text-color-primary);
  }

  td.el-table__cell {
    border-bottom-color: var(--el-border-color-lighter);
  }

  .el-table__body tr:hover > td {
    background: var(--el-fill-color-light);
  }
}

// 统计卡片悬停效果增强
.stats-card {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--el-box-shadow-light);
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .dashboard {
    .stats-grid {
      grid-template-columns: repeat(2, 1fr);
    }

    .charts-row,
    .info-row {
      .el-col {
        &:first-child,
        &:last-child {
          width: 100%;
          margin-bottom: 20px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .dashboard {
    .stats-grid {
      grid-template-columns: 1fr;
    }

    .charts-row,
    .info-row {
      .el-col {
        width: 100%;
      }
    }
  }
}
</style>